package config

import (
	"fmt"
	"log"
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Server struct {
		Port int `yaml:"port"`
	} `yaml:"server"`

	Database struct {
		User   string `yaml:"user"`
		Pass   string `yaml:"password"`
		Host   string `yaml:"host"`
		Port   int    `yaml:"port"`
		DBName string `yaml:"dbname"`
	} `yaml:"database"`

	Jwt struct {
		Secret string `yaml:"secret"`
		Expire int    `yaml:"expire"`
	} `yaml:"jwt"`

	DeepSeek struct {
		APIUrl         string        `yaml:"api_url"`
		ApiKey         string        `yaml:"api_key"`
		Timeout        time.Duration `yaml:"timeout"`
		AlertThreshold float64       `yaml:"alert_threshold"`
		Enable         bool          `yaml:"enable"`
	} `yaml:"deepseek"`
}

var AppConfig *Config

// InitConfig read and load configuration file
func InitConfig() {
	data, err := os.ReadFile("config/config.yaml")
	if err != nil {
		log.Fatalf("Read Configuration file error: %v", err)
	}

	var cfg Config
	err = yaml.Unmarshal(data, &cfg)
	if err != nil {
		log.Fatalf("Unmarshal error: %v", err)
	}

	AppConfig = &cfg
	fmt.Println("Configuration file loaded successfully")
}

// GetDSN return mysql dsn and connect string
func GetDSN() string {
	db := AppConfig.Database
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		db.User, db.Pass, db.Host, db.Port, db.DBName)
}
